/*
 * SilkRAR.java
 *
 * Created May 11, 2006
 * David Connell
 * Copyright (c) 2005 Synergy Systems, Inc
 */
package org.puresilk.afx.util;

import org.jdom.*;
import org.puresilk.afx.SilkAfxException;
import org.puresilk.afx.util.SilkAfxXMLRequest;

/**
 * A wrapper for the SilkAfxXMLRequest that 
 * fires Remote Action Requests and hands 
 * back the responseor throws exceptions if  
 * there is a problem.
 */
public class SilkRAR {
	private String rpcUrl = null;
	
	/** default constructor */
	public SilkRAR() {
		
	}
	
	/** constructor w/ target */
	public SilkRAR(String targetURL){
		rpcUrl = targetURL;
	}
	
	/** Executes the RPC */
	public Element fire(String params) throws SilkAfxException {
		Element resp = null;
		
		if (rpcUrl == null)
			throw new SilkAfxException("Invalid Target Url (null)");
		
		Document d = SilkAfxXMLRequest.getResponse(rpcUrl,params);
		
		try {
			// extract the response and the message
			Element hdr = d.getRootElement().getChild("wxResponseHeader");
			String rc = hdr.getChildText("wxResultCode").trim();
			String msg = hdr.getChildText("wxMessage").trim();
			
			// make sure it worked
			if (rc.charAt(0) != '1'){
				throw new SilkAfxException("WorxRPC Error " + rc + ": " + msg);
			}

			// extract content of response element 
			resp = (Element)d.getRootElement().getChild("wxResponse").getChildren().get(0);
		}
		catch(Exception ex) {
			throw new SilkAfxException(ex);
		}
		
		// return response
		return resp; 
	}

	public void setTargetURL(String url) {
		rpcUrl = url;
	}
	
	public String getTargetURL(){
		return rpcUrl;
	}
}
